<?php
include_once BASE_PATH.'drive/PhotoCollect.class.php';
class HkCollect{
	public $site_url  = 'http://www.60kh.com/';
	private $list_rule = '';
	public function __construct(){
	}
	public function run(){
		$list         = $this->getList();




		$content_list = $this->getContentListByListURL($list_url);
		/**
		 * 获取图片地址
		 */
		foreach($content_list as $k=> $v){
			$content_list[$k]['image_list'] =  $this->getImageListByContentURL($v['url']);
		}
		foreach($content_list as $v){
			$this->downloadImage($v);
		}
	}
	public function downloadImage($node_info){
		echo 'download:',$node_info['title'];
		$dir = SAVE_PATH.'/'.$node_info['title'];
		if(!is_dir($dir)){mkdir($dir);}
		$i = 0;
		foreach($node_info['image_list'] as $v){
			$ext = end(explode('.',$v));
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n" .
			  "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11\n\n"
			  
  )
);

$context = stream_context_create($opts);



			file_put_contents($dir.'/'.$i.'.'.$ext,file_get_contents($v,false,$context));
			echo 'save',$dir.'/'.$i.'.'.$ext,"\n";
			$i++;
		}

	}
	public function getImageListByContentURL($content_url){
		$content =  file_get_contents($content_url);
		preg_match('/\<div class=\"c4\".*?\<\/div\>/is',$content,$list_div);
		preg_match_all('/\<img src=\"(.*)\".*\>/isU',$list_div[0],$image_list);
		return $image_list[1];
	}
	public function getContentListByListURL($list_url){
		$list_content = file_get_contents($list_url);
		$content_list = array();
		$list_div = '';
		preg_match('/\<div class=list(.*?)\<\/div\>/is',$list_content,$list_div);
		preg_match_all('/\<li\>.*\<a href=(?P<url>.*) .* title=(?P<title>.*)>.*\<\/a\>/isU',$list_div[0],$content_list);
		$list = array();
		$node = array();
		foreach($content_list['url'] as $k => $v){
			$node['url']= str_replace('../','',$this->site_url.$v);
			$node['title'] = $content_list['title'][$k];
			$list[] = $node;
		}
		return $list;
	}
	/**
	 * 获取图片分类列表
	 * 一般写死
	 */
	public function getList(){
		$list = array(
				'http://www.60kh.com/List_feizhuliu/3387407_54_{#page}.html',
			);
		$list_list = array();
		foreach($list as $v){
			$i = 1 ;
			while(1){
				$list_url = str_replace('{#page}',$i,$v);
				$header = get_headers($list_url);
				if($header[0] != 'HTTP/1.1 200 OK'){
					break;
				}
				echo '获取网址:',$list_url,"\n";
				$list_list[]=$list_url;
				$i++;
			}

		}
		return $list_list;
	}
}